package com.niit.dao.impl;

import java.util.List;

import com.niit.bean.User;
import com.niit.dao.UserDao;
import com.niit.utils.DbUtil;
import com.niit.utils.WebKit;

public class UserDaoImpl implements UserDao {

	private DbUtil util = new DbUtil();

	@Override
	public int add(User t) {
		// 循环随机产生用户名
		String name = WebKit.getUsername();
		String checkExist = "select count(*) from tb_user where username ='"+name+"'";
		int exist = util.selectCount(checkExist);
		while (exist != 0) {
			name = WebKit.getUsername();
			exist = util.selectCount("select count(*) from tb_user where username ='"+name+"'");
		}
		String sql = "insert into tb_user(username,password,mobile,email,validation) values(?,?,?,?,?)";
		int a = util.update(sql,name, t.getPassword(),
				t.getMobile(), t.getEmail(),t.isValidation());
		String sql1="insert into tb_user_info (username) values (?)";
		util.update(sql1, name);//将用户名插入tb_user_info
		return a;
	}

	@Override
	public int delete(User t) {
		String sql = "delete from tb_user where username=?";
		int a = util.update(sql, t.getUsername());
		return a;
	}

	@Override
	public int update(User t) {
		String sql = "update tb_user set password=?,mobile=?,email=? where username=?";
		int a = util.update(sql,  t.getPassword(),
				t.getMobile(), t.getEmail(),t.getUsername());
		return a;
	}

	@Override
	public List<User> findAll(int start, int end) {
		String sql = "select * from(select rownum r,tb_user.* from tb_user) a where a.r>? and a.r<=?";
		List<User> list = util.select(sql, User.class, start, end);
		return list;
	}

	@Override
	public int findTotal() {
		String sql = "select count(*) from tb_user ";
		int count = util.selectCount(sql);
		return count;
	}

	@Override
	public boolean usernameExist(String username) {
		String sql = "select * from tb_user where username = ?";
		List<User> list = util.select(sql, User.class, username);
		return list==null?false:true;
	}

	@Override
	public boolean isMobExist(String mobile) {
		String sql = "select count(*) from tb_user where mobile=?";
		return util.selectCount(sql, mobile)>0?true:false;
	}

	@Override
	public boolean isEmailExist(String email) {
		String sql = "select count(*) from tb_user where email=?";
		return util.selectCount(sql, email)>0?true:false;
	}

	@Override
	public User login(String username, String password) {
		String sql = "select * from tb_user where (username=? or mobile=? or email=?) and password=?";
		List<User> list = util.select(sql, User.class, username, username, username,password);
		return list==null?null:list.get(0);
	}
	
	public int update(boolean forbid, String username) {
		String sql = "update tb_user set forbid=? where username=?";
		int a = util.update(sql, forbid, username);
		return a;
	}


}
